﻿using EventMgrLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionRoc.Core;

namespace VisionRoc_Measure
{
    public partial class FormTCPClientTool : Form
    {
        TCPClient m_TCPClient;
        public FormTCPClientTool(TCPClient _TCPClient)
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景 
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲  
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.DoubleBuffered = true;//避免时间显示控件闪烁
            InitializeComponent();
            m_TCPClient = _TCPClient;
            Control.CheckForIllegalCrossThreadCalls = false;//取消跨线程访问
        }

        private void FormTCPClientTool_Load(object sender, EventArgs e)
        {
            EventMgr.Ins.GetEvent<LogEvent>().Subscribe(LogHandle, log => log.SolutionName == "Main");  //接受外部发步的记录日志的事件
            m_TCPClient.ReadParameter();
            if (m_TCPClient.ConnectState)
            {
                txt_IP.Text = m_TCPClient.IP;
                txt_Port.Text = m_TCPClient.Port.ToString();

                txt_IP.Enabled = false;
                txt_Port.Enabled = false;
                checkBox1.Enabled = false;
                btn_Connect.Enabled = false;
                btn_Close.Enabled = true;
                btn_SendMsg.Enabled = true;
                btn_SaveParameter.Enabled = false;

            }
            else
            {
                txt_IP.Text = m_TCPClient.IP;
                txt_Port.Text = m_TCPClient.Port.ToString();

                txt_IP.Enabled = true;
                txt_Port.Enabled = true;
                checkBox1.Enabled = true;
                btn_Connect.Enabled = true;
                btn_Close.Enabled = false;
                btn_SendMsg.Enabled = false;
                btn_SaveParameter.Enabled = true;
            }
            if (m_TCPClient.ReconnectState == 1)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }
        }

        private void LogHandle(LogPayload obj)
        {
            AddLogListView(obj.Level, obj.LogMessage);
        }

        object log = new object();
        /// <summary>
        /// 全程日志记录 不会报异常
        /// </summary>
        /// <param name="level"></param>
        /// <param name="Log"></param>
        public void AddLogListView(int level, string Log)
        {
            lock (log)
            {
                Thread.Sleep(5);
                //日志显示控件记录 通过委托的方式 全部主线程记录 不会报跨线程异常
                //判断是否是跨线程访问
                if (!this.lstInfo.InvokeRequired)
                {
                    if (Global.LogCount > 0)
                    {
                        //显示日志的显示数量 防止内存溢出
                        if (lstInfo.Items.Count >= Global.LogCount)
                        {
                            lstInfo.Items.RemoveAt(lstInfo.Items.Count - 1);
                        }
                        ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString(" HH:mm:ss ff"), level);
                        lst.SubItems.Add(Log);
                        lstInfo.Items.Insert(0, lst);
                    }
                    else if (Global.LogCount < 0)
                    {
                        ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                        lst.SubItems.Add(Log);
                        lstInfo.Items.Insert(0, lst);
                    }
                }
                else
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        try
                        {
                            if (Global.LogCount > 0)
                            {
                                //显示日志的显示数量 防止内存溢出
                                if (lstInfo.Items.Count >= Global.LogCount)
                                {
                                    lstInfo.Items.RemoveAt(lstInfo.Items.Count - 1);
                                }
                                ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                                lst.SubItems.Add(Log);
                                lstInfo.Items.Insert(0, lst);
                            }
                            else if (Global.LogCount < 0)
                            {
                                ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                                lst.SubItems.Add(Log);
                                lstInfo.Items.Insert(0, lst);
                            }
                        }
                        catch { }
                    }));
                }
            }
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPClient.IP = txt_IP.Text;
                m_TCPClient.Port = Convert.ToInt32(txt_Port.Text);
                if (m_TCPClient.Connect())
                {
                    txt_IP.Enabled = false;
                    txt_Port.Enabled = false;
                    checkBox1.Enabled = false;
                    btn_Connect.Enabled = false;
                    btn_Close.Enabled = true;
                    btn_SendMsg.Enabled = true;
                    btn_SaveParameter.Enabled = false;
                }
                else
                {
                    txt_IP.Enabled = true;
                    txt_Port.Enabled = true;
                    checkBox1.Enabled = true;
                    btn_Connect.Enabled = true;
                    btn_Close.Enabled = false;
                    btn_SendMsg.Enabled = false;
                    btn_SaveParameter.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPClient.CloseClient();
                txt_IP.Enabled = true;
                txt_Port.Enabled = true;
                checkBox1.Enabled = true;
                btn_Connect.Enabled = true;
                btn_Close.Enabled = false;
                btn_SendMsg.Enabled = false;
                btn_SaveParameter.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btn_SendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                if (txt_Msg.Text.Trim().Length > 0)
                {
                    m_TCPClient.Send(txt_Msg.Text.Trim());
                }
                else
                {
                    MessageBox.Show("发送至客户端消息不能为空！也不能有空格。");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btn_SaveParameter_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPClient.IP = txt_IP.Text;
                m_TCPClient.Port = Convert.ToInt32(txt_Port.Text);
                if (checkBox1.Checked)
                {
                    m_TCPClient.ReconnectState = 1;
                }
                else
                {
                    m_TCPClient.ReconnectState = 2;
                }
                m_TCPClient.WriteParameter();
                MessageBox.Show("保存成功.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void FormTCPClientTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            EventMgr.Ins.GetEvent<LogEvent>().Unsubscribe(LogHandle);
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
